package cn.elead.chaos.framework.web.global;

import java.io.Serializable;
import java.time.LocalDateTime;

import javax.servlet.http.HttpServletResponse;

import org.springframework.http.server.ServerHttpResponse;

import cn.elead.chaos.framework.util.ResponseUtils;

import cn.hutool.http.HttpStatus;

/**
 * 接口返回(多态)
 * 
 * @author luopeng
 *
 * @param <T>
 */
public class ApiResponse<T> implements Serializable {

	/**
	 * 序列
	 */
	private static final long serialVersionUID = -1296644476749112463L;

	/**
	 * 不需要返回结果
	 *
	 * @param status
	 */
	public static ApiResponse<Void> success(HttpServletResponse response, int code) {
		response.setStatus(code);
		return SuccessResponse.<Void>builder().code(code).build();

	}

	/**
	 * 成功返回
	 *
	 * @param object
	 */
	public static <T> ApiResponse<T> success(T object) {
		return success(HttpStatus.HTTP_OK, object);
	}

	/**
	 * 成功返回
	 *
	 * @param object
	 */
	public static <T> ApiResponse<T> success(int code, T object) {
		return SuccessResponse.<T>builder().code(code).data(object).build();
	}

	/**
	 * 成功返回
	 *
	 * @param status
	 * @param object
	 */
	public static <T> ApiResponse<T> success(HttpServletResponse response, T object) {
		return SuccessResponse.<T>builder().code(HttpStatus.HTTP_OK).data(object).build();
	}

	/**
	 * 成功返回
	 *
	 * @param status
	 * @param object
	 */
	public static <T> ApiResponse<T> success(HttpServletResponse response, int status, T object) {
		response.setStatus(status);
		return SuccessResponse.<T>builder().code(status).data(object).build();
	}
	
	/**
     * 成功返回
     *
     * @param status
     * @param object
     */
    public static <T> ApiResponse<T> success(ServerHttpResponse response, int status, T object) {
        response.setStatusCode(org.springframework.http.HttpStatus.valueOf(status));
        return SuccessResponse.<T>builder().code(status).data(object).build();
    }

	
	/**
	 * 失败返回
	 *
	 * @param errorCode
	 * @param exception
	 */
	public static <T> ApiResponse<T> failure(ErrorCodeEnum ErrorCodeEnum, Exception exception) {
		ErrorCode errorCode = ErrorCodeEnum.convert();
		return failure(errorCode, exception);
	}
	
	/**
	 * 失败返回
	 *
	 * @param errorCode
	 * @param exception
	 */
	@SuppressWarnings("unchecked")
	public static <T> ApiResponse<T> failure(ErrorCode errorCode, Exception exception) {
		return ResponseUtils.exceptionMsg(FailedResponse.<T>builder()
				.msg(errorCode.getMsg()), exception)
				//.exception(TypeUtils.castToString(exception))
				.time(LocalDateTime.now())
				.code(errorCode.getCode()).build();
	}

	/**
	 * 失败返回
	 *
	 * @param errorCode
	 * @param exception
	 */
	public static <T> ApiResponse<T> failure(ErrorCode errorCode) {
		return failure(errorCode, null);
	}

}
